<!--
 * @Author: lh
 * @Date: 2023-07-11 13:52:31
 * @LastEditors: lh
 * @LastEditTime: 2023-10-20 18:00:54
-->
<template>
  <div>
    <!-- :searchDataList="searchDataListJy" -->
    <!-- <personnel></personnel> -->
    <tabCom
      @Refresh="Refresh"
      @search-callback="searchCallback"
      :title="'设计文件分发'"
      :operation-api="operationApiA"
      :table-data-rule="tableDataRuleA"
      :search-data-list="searchDataListJy"
      :needPagination="true"
      :update_show_key="'id'"
      :update_show_value="[0]"
      :formDataWidth="'30%'"
      :isAddArr="false"
      :isUpdataArr="true"
      :addButtonList="addButtonList"
      @buttonMoudle="buttonMoudle"
      ref="tabCombox"
    >
      <template #add="{ formData }">
        <el-form-item :label="item.title" v-for="(item, index) in searchDataListJyEdit" :key="index">
          <el-input v-if="!item.type" v-model="formData[item.name]" placeholder="请输入" />
          <personnel v-model="formData[item.name]" v-else-if="item.type == 'user'"></personnel>
          <personnelMore v-model="formData[item.name]" v-else-if="item.type == 'userMore'"></personnelMore>
          <el-select
            v-else-if="item.type == 'search_select'"
            v-model="formData[item.name]"
            filterable
            remote
            reserve-keyword
            placeholder="请输入设计文件名称查询"
            remote-show-suffix
            :remote-method="remoteMethod"
            :loading="loadingSel"
          >
            <el-option v-for="item in optionsSel" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
          <el-input
            v-else-if="item.type == 'number'"
            type="number"
            v-model="formData[item.name]"
            placeholder="请输入"
          />
          <!-- value-format="YYYY/MM/DD" -->
          <el-date-picker
            v-else-if="item.type == 'timeday'"
            v-model="formData[item.name]"
            type="date"
            format="YYYY/MM/DD"
            placeholder="请选择"
          />
          <el-date-picker
            v-else-if="item.type == 'datetime'"
            v-model="formData[item.name]"
            type="datetime"
            format="YYYY/MM/DD HH:mm:ss"
            placeholder="请选择"
          />
          <upfilebox
            v-else-if="item.type == 'file'"
            fileType="file"
            v-model="formData[item.name]"
            v-model:name="formData[item.prop]"
          ></upfilebox>
          <el-date-picker
            @change="chooseTimeChange(formData[item.name])"
            v-else-if="item.type == 'time'"
            v-model="formData[item.name]"
            type="datetimerange"
            format="YYYY/MM/DD"
            value-format="YYYYMMDD"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
          />
          <el-select
            v-else-if="item.type == 'select' && item!.list!.length > 0"
            v-model="formData[item.name]"
            default-first-option
            :reserve-keyword="false"
            clearable
            allow-create
            filterable
            placeholder="请选择"
          >
            <el-option
              v-for="items in item.list"
              :key="items.value"
              :label="items.label || items.name"
              :value="items.value || items.id"
            />
          </el-select>
          <el-select
            v-else-if="item.type == 'selectLable'"
            v-model="formData[item.name]"
            default-first-option
            :reserve-keyword="false"
            clearable
            filterable
            placeholder="请选择"
          >
            <el-option
              v-for="items in item.list"
              :key="items.value"
              :label="items.label || items.name"
              :value="items.label || items.name"
            />
          </el-select>
          <el-select
            v-else-if="item.type == 'multipleSelect'"
            multiple
            v-model="formData[item.name]"
            default-first-option
            :reserve-keyword="false"
            clearable
            filterable
            placeholder="请选择"
          >
            <el-option
              v-for="items in item.list"
              :key="items.value"
              :label="items.label || items.name"
              :value="items.label || items.name"
            />
          </el-select>
        </el-form-item>
      </template>
      <template #designFileId="{ data }">
        <el-tooltip class="box-item" effect="dark" content="点击查看设计文件详情" placement="top">
          <div @click="showDetailsOpen(data)">{{ data.designFileId }}</div>
        </el-tooltip>
      </template>
      <template #examinationState="{ data }">
        <div style="width: 100%">
          <el-steps :active="data.lettersState" :align-center="true" finish-status="success">
            <el-step title="总监审核" />
            <el-step title="部门审核" />
            <el-step title="主办人审核" />
          </el-steps>
        </div>
      </template>
    </tabCom>
    <!-- 启动审查 -->
    <el-dialog v-model="dialogVisible" :title="'部门负责人操作'" @close="resetForm" width="30%">
      <el-form ref="formRef" label-width="100px" label-position="left">
        <el-form-item prop="actionItemEvolve" label="分配相关接口人">
          <personnelMore v-model="actionItemEvolve"></personnelMore>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreate">确认</el-button>
      </template>
    </el-dialog>
    <!-- 总监分发 -->
    <el-dialog v-model="zjFfData.dialogVisible" :title="'总监分发'" @close="resetFormzjFfData" width="30%">
      <el-form ref="formRef" label-width="100px" label-position="left">
        <el-form-item label="设置分发类型">
          <el-radio-group v-model="zjFfData.distributionType" class="ml-4">
            <el-radio :label="1" size="large">分发到部门</el-radio>
            <el-radio :label="2" size="large">分发到主办人</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="责任部门">
          <el-input v-model="zjFfData.responsibleDepartment" placeholder="请输入" />
        </el-form-item>
        <el-form-item :label="zjFfData.distributionType == 1 ? '部门负责人' : '主办人'">
          <personnel v-model="zjFfData.distributionUserId"></personnel>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="zjFfData.dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="CloseTaskFnConfim">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import tabCom from "@/components/table/indexcopy.vue"
// import { gethomeStatistics } from "@/api/home/index"
import { ref, onMounted, reactive } from "vue"
import upfilebox from "@/components/table/upfile.vue"
import { useUserStoreHook } from "@/store/modules/user"
import { ElMessage, ElMessageBox } from "element-plus"
import { userInitiateReviewProcess } from "@/api/procedure"
import { selectAlldesignFile, allocationInterfacePerson, interfacePersonDetermine } from "@/api/designfile"
import { selectOne, directorDistributionDesignFile } from "@/api/designfile"
import { useRouter } from "vue-router"

const { userId } = useUserStoreHook()
const tabCombox = ref<typeof tabCom>()
let useRouterHook = useRouter()

onMounted(() => {
  init()
})
// 接口请求配置
const operationApiA = ref<any>([
  { type: "add", interface: "/designFileDistribute/createDistributionOrder" },
  { type: "update", interface: "/designFileDistribute/insertOrUpdate" },
  { type: "search", interface: "/designFileDistribute/selectAll" },
  { type: "delete", interface: "/designFileDistribute/deleteByIds" },
  { type: "svg", interface: "/designFileDistribute/export" }
])
//#region  添加按钮所有逻辑
// 添加按钮
const addButtonList = [
  {
    name: "总监分发",
    type: "CloseTask",
    show: {
      name: "distributeState",
      value: 0
    }
  },
  {
    name: "部门负责人操作",
    type: "infill",
    show: {
      name: "distributeState",
      value: 1
    }
  },
  {
    name: "文档接口人操作",
    type: "validation",
    show: {
      name: "distributeState",
      value: 2
    }
  }
]
const tablerow = ref() // 当前操作表单数据
// 按钮回调
const buttonMoudle = (type: string, row: any, Face: string) => {
  tablerow.value = row
  console.log(type, row, "-*-buttonMoudle")
  switch (type) {
    case "infill": // 部门负责人操作
      infillFn()
      break
    case "validation": // 文档接口人操作
      validationFn()
      break
    case "CloseTask": // 设计文件分发
      CloseTaskFn()
      break
  }
}

// 总监分发参数
let zjFfData = reactive({
  distributionType: 1, // 分发类型
  distributionUserId: "", // 分发人id
  responsibleDepartment: "", // 责任部门
  dialogVisible: false // 弹框
})
// 重置
const resetFormzjFfData = () => {
  zjFfData.dialogVisible = false
  zjFfData.distributionType = 1
  zjFfData.distributionUserId = ""
}
// 确认总监审核
const CloseTaskFnConfim = () => {
  if (!zjFfData.distributionUserId) {
    ElMessage.error("请选中处理人~")
    return
  }
  directorDistributionDesignFile({
    id: tablerow.value.id,
    ...zjFfData
  }).then((res) => {
    if (res.code == 200) {
      ElMessage({ message: "提交成功", type: "success" })
      resetFormzjFfData()
      tabCombox.value.resetSearch()
    }
  })
}

// 总监审核
const CloseTaskFn = () => {
  // 当前还没验证
  let batchDivisionInfoo = tablerow.value.directorUids
  if (userId == batchDivisionInfoo) {
    zjFfData.dialogVisible = true
  } else {
    ElMessage.error("你不是该审核人~")
  }
}

let dialogVisible = ref(false) // 启动审查弹框
let actionItemEvolve = ref("") // 审查相关人(各部门负责人用户ids(多个用英文逗号隔开)--审查)
// 填写反馈行动项进展 方法
const infillFn = () => {
  if (tablerow.value.distributeState == 1) {
    let tabresponsibleDepartmentUids = tablerow.value?.responsibleDepartmentUids.split(",") || []
    if (tabresponsibleDepartmentUids.includes(userId.toString())) {
      dialogVisible.value = true
    } else {
      ElMessage.error("你不是该部门处理人~")
    }
  } else {
    ElMessage.error("已操作~")
  }
}
// 重置数据
const resetForm = () => {
  actionItemEvolve.value = ""
}
// 确认反馈
const handleCreate = () => {
  if (!actionItemEvolve.value) {
    ElMessage.error("请选择分配相关接口人")
    return
  }
  allocationInterfacePerson({
    professionalSupervisionEngineerUids: actionItemEvolve.value,
    id: tablerow.value.id
  }).then((res) => {
    console.log(res, "---res")

    if (res.code == 200) {
      ElMessage({ message: "提交成功", type: "success" })
      tabCombox.value.resetSearch()
      dialogVisible.value = false
      resetForm()
    }
  })
}
// 文档接口人操作
const validationFn = () => {
  if (tablerow.value.distributeState == 2) {
    let tabprofessionalSupervisionEngineerUids = tablerow.value?.professionalSupervisionEngineerUids.split(",") || []
    if (tabprofessionalSupervisionEngineerUids.includes(userId.toString())) {
      ElMessageBox.confirm("请确认?", "接口人确认文件设计", {
        confirmButtonText: "确认",
        cancelButtonText: "取消"
      })
        .then(() => {
          interfacePersonDetermine({
            id: tablerow.value.id
          }).then((res) => {
            if (res.code == 200) {
              ElMessage({ message: "提交成功", type: "success" })
              tabCombox.value.resetSearch()
              resetForm()
            }
          })
        })
        .catch(() => {})
    } else {
      ElMessage.error("你不是该接口人~")
    }
  } else {
    if (tablerow.value.status < 2) {
      ElMessage({
        message: "还没到当前步骤",
        type: "warning"
      })
    } else {
      ElMessage({
        message: "已操作",
        type: "warning"
      })
    }
  }
}

//#endregion

//#region  选择设计表

interface ListItem {
  value: string
  label: string
}

const listSel = ref<ListItem[]>([])
const optionsSel = ref<ListItem[]>([])
const loadingSel = ref(false)

const remoteMethod = (query: string) => {
  if (query) {
    loading.value = true
    // setTimeout(() => {
    //   loading.value = false
    //   optionsSel.value = listSel.value.filter((item) => {
    //     return item.label.toLowerCase().includes(query.toLowerCase())
    //   })
    // }, 200)
    selectAlldesignFile({
      page: 1,
      pageSize: 10,
      associationState: 0,
      projectName: query
    })
      .then((res) => {
        if (res.code == 200) {
          let datalist = res.data.records
          optionsSel.value = datalist.map((item) => {
            return {
              value: item.id,
              label: item.designFileName
            }
          })
        }
        loading.value = false
      })
      .catch(() => {
        loading.value = false
      })
  } else {
    optionsSel.value = []
  }
}

//#endregion

// 搜索配置
const searchDataListJy = [
  { name: "id", title: "id" },
  { name: "designFileId", title: "设计文件主键id" },
  { name: "distributeNum", title: "文件分发单编码" },
  { name: "responsibleDepartment", title: "责任部门" },
  { name: "startTime", title: "开始时间", type: "datetime" },
  { name: "endTime", title: "结束时间", type: "datetime" }
]
// 添加配置
const searchDataListJyEdit = [
  { name: "id", title: "设计文件主键ID", type: "search_select" },
  {
    name: "distributionType",
    title: "分发类型",
    type: "select",
    list: [
      { value: 1, label: "总监分发" },
      { value: 2, label: "部门分发" },
      { value: 3, label: "文档接口人处理" }
    ]
  },
  { name: "responsibleDepartment", title: "责任部门" },
  { name: "distributionUserIds", title: "相关处理人", type: "user" }
]
// 表单配置
const tableDataRuleA = ref([
  { prop: "id", label: "id" },
  { prop: "designFileId", label: "设计文件主键id", slot: "designFileId" },
  { prop: "distributeNum", label: "文件分发单编码	" },
  { prop: "createUserName", label: "监理文档人员" },

  { prop: "responsibleDepartment", label: "责任部门	" },
  { prop: "responsibleDepartmentName", label: "责任部门负责人" },
  { prop: "directorName", label: "总监姓名" },
  { prop: "professionalSupervisionEngineerName", label: "专业监理工程师" },

  {
    prop: "distributeState",
    label: "分发状态",
    type: "select",
    list: [
      { value: 0, label: "总监待分发", name: "总监待分发", id: 0 },
      { value: 1, label: "责任部门待分发", name: "责任部门待分发", id: 1 },
      { value: 2, label: "文档接口人待分发确认", name: "文档接口人待分发确认", id: 2 },
      { value: 3, label: "完成", name: "完成", id: 3 }
    ]
  },
  { prop: "remarks", label: "备注" }
  // {prop: 'operate',label: '操作'},
])
// 初始化
const init = () => {}
// 表单刷新
const Refresh = () => {
  //用户数据概览
}
// 搜索回调
const searchCallback = (search: any) => {}
const loading = ref<boolean>(false)
const gailan = ref<any>({})
const gethomeStatisticsStar = (obj: any = {}) => {
  // loading.value = true
  // gethomeStatistics(obj).then((res: any) => {
  //   gailan.value = res.data
  //   loading.value = false
  // })
}

// 时间选择限定范围
const chooseTimeChange = (time: any) => {
  const starTime = JSON.parse(JSON.stringify(time[0]))
  const endTime = JSON.parse(JSON.stringify(time[1]))
  const minTime = new Date(insertStr(insertStr(starTime, 4, "-"), 7, "-")).getTime()
  const maxTime = new Date(insertStr(insertStr(endTime, 4, "-"), 7, "-")).getTime()
  const allow = 2592000000 //30天
  if (maxTime - minTime > allow) {
    ElMessage.warning("选择范围请在30天以内!")
    chaxunState.value = false
  } else {
    chaxunState.value = true
  }
}

// 查看设计文件录入详情
const showDetailsOpen = (it: any) => {
  console.log(it, "--showDetailsOpen-")
  selectOne(it.designFileId).then((res) => {
    // console.log(res,'--selectOne-');
    if (res.code == 200) {
      let data = res.data
      localStorage.setItem(
        "tableDataRule",
        JSON.stringify([
          { prop: "id", label: "id" },
          { prop: "designFileNum", label: "设计文件编码" },
          { prop: "projectName", label: "项目名称" },
          { prop: "atlasNum", label: "图册编号" },
          { prop: "designFileName", label: "设计文件名称" },
          { prop: "fileVersion", label: "版本" },
          { prop: "fileState", label: "状态" },
          { prop: "sharedDepartment", label: "共享部门" },
          { prop: "position", label: "存放位置" },
          { prop: "organizationUnit", label: "编制单位" },
          { prop: "organizationTime", label: "编制日期", type: "time" },
          { prop: "fileType", label: "文件类型" },
          { prop: "supervisionResponsiblePersonName", label: "监理责任人" },
          { prop: "responsiblePersonCollectionTime", label: "责任人收图日期" },
          { prop: "filename", label: "附件文件", type: "fileUrl", assoc: "fileName" },
          { prop: "readingTimeLimit", label: "阅图时间限制(单位分钟)" },
          { prop: "readingState", label: "阅图状态" },
          { prop: "dispatchesTime", label: "收文日期", type: "time" },
          { prop: "distributionState", label: "分发状态" },
          { prop: "remarks", label: "备注" }
        ])
      )
      localStorage.setItem("rowTable", JSON.stringify(data))
      localStorage.setItem("rowTableName", "设计文件接受/著录/导入")
      useRouterHook.push({
        path: "/tableDetails"
      })
    }
  })
}
</script>
<style scoped lang="scss">
.search-wrapper {
  margin: 0 auto;
  width: 98.5%;
  margin-top: 10px;
}
</style>
